package com.chinasoft.gw.filter;

import com.chinasoft.gw.utils.JsonUtils;
import com.chinasoft.gw.utils.JwtUtils;
import com.chinasoft.ms.pojo.MyToken;
import com.chinasoft.ms.pojo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.netty.ByteBufFlux;

import java.net.URI;
import java.util.List;

@Component
@Order(-1)
public class AuthFilter implements GlobalFilter {

    /**
     * 自定义过滤器方法，用于处理进入网关的每个请求
     * 该方法主要检查查询参数中的授权信息，以决定是否放行请求
     *
     * @param exchange 服务器Web交换对象，包含请求和响应的所有信息
     * @param chain 网关过滤器链，用于执行下一个过滤器或最终的请求处理
     * @return Mono<Void> 表示异步处理完成的响应
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取当前请求
        ServerHttpRequest request = exchange.getRequest();
        URI uri = request.getURI();
        if(uri.getPath().contains("login")) {
            System.out.println("url is " + uri.getPath());
            return chain.filter(exchange);
        }
        if(uri.getPath().contains("register")) {
            System.out.println("url is " + uri.getPath());
            return chain.filter(exchange);
        }
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("Authorization");
        System.out.println(token);
        if (token != null && token.length() > 0 && JwtUtils.verifyToken(token)) {
            // 放行
            String strUserId = JwtUtils.getAudience(token);
//            Long userId = Long.parseLong(strUserId);
            System.out.println(strUserId);
            request.mutate().header("userId", strUserId);
//            headers.add("userId", strUserId);
            return chain.filter(exchange);
        }
        //  给前端一个响应
        Result<Object> result = new Result<Object>(555, "令牌无效，请登录 ！", null);

        String json = JsonUtils.objectToJson(result);

        // 如果不是"admin"，获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        // 设置响应状态码为403 FORBIDDEN
        response.setStatusCode(HttpStatus.OK);
        // 完成响应，结束请求处理
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");

        return response.writeAndFlushWith(Flux.just(ByteBufFlux.just(response.bufferFactory().wrap(json.getBytes()))));
    }
}
